import { App } from "vue";
import hl from "highlight.js"; // 导入代码高亮文件
import { toast } from "@/hooks/useToast";
// 自定义一个代码高亮指令
const createCopy = (el: HTMLElement) => {
  //插入复制功能
  const code = el.getElementsByTagName("code")[0];
  const copy = document.createElement("div");
  copy.classList.add("hljs-copy");
  const lang = el.getElementsByTagName("table")[0];
  const langText = lang.dataset.lang;
  copy.innerHTML = `<span class="lang-box">${langText}</span> <span class="iconfont icon-xinAPPtubiaoPython_bianjiqi copy-box"></span>`;
  //添加点击事件
  copy.addEventListener("click", () => {
    //创建一个输入框
    const textarea = document.createElement("textarea");
    document.body.appendChild(textarea);
    textarea.setAttribute("readonly", "readonly");
    textarea.value = code.innerText;
    textarea.select();
    if (document.execCommand("copy")) {
      document.execCommand("copy");
      //   copy.innerHTML = "<span>复制成功</span>";
      toast("复制成功!");
    }
    document.body.removeChild(textarea);
  });

  el.insertBefore(copy, el.firstChild);

  //   //鼠标移入显示复制按钮
  //   code.addEventListener("mouseout", () => {
  //     copy.innerText = "复制";
  //     copy.style.display = "none";
  //   });
  //   code.addEventListener("mouseover", () => {
  //     copy.style.display = "block";
  //   });
};
const plugin = {
  install(app: App): void {
    app.directive("highlight", function (el) {
      const blocks: HTMLElement[] = el.querySelectorAll("pre code");
      blocks.forEach((block) => {
        hl.highlightBlock(block);
        block.parentElement && createCopy(block.parentElement);
      });
    });
  },
};
export default plugin;
